use crossterm::event::KeyCode;

use crate::pet_anime::PetAnimationManager;
use crate::pet_config::{PetConfig, MoodState, PetType};

pub struct PetAction {
    config: PetConfig,
    input_buffer: String,
    show_help: bool,
}

impl PetAction {
    pub fn new(config: PetConfig) -> Self {
        Self {
            config,
            input_buffer: String::new(),
            show_help: false,
        }
    }
    
    pub fn handle_input(&mut self, key_code: KeyCode, animation: &mut PetAnimationManager) -> bool {
        // 更新时间衰减
        self.config.update_time_decay();
        
        match key_code {
            KeyCode::Char(c) => {
                if c == '/' || !self.input_buffer.is_empty() {
                    self.input_buffer.push(c);
                    true
                } else {
                    // 非命令模式下的按键作为抚摸
                    self.pet_cat(animation);
                    true
                }
            },
            KeyCode::Enter => {
                if !self.input_buffer.is_empty() {
                    let result = self.process_command(animation);
                    self.input_buffer.clear();
                    result
                } else {
                    self.pet_cat(animation);
                    true
                }
            },
            KeyCode::Backspace => {
                if !self.input_buffer.is_empty() {
                    self.input_buffer.pop();
                }
                true
            },
            KeyCode::Esc => {
                self.input_buffer.clear();
                self.show_help = false;
                true
            },
            _ => {
                // 其他按键也算作抚摸（如果不在命令模式）
                if self.input_buffer.is_empty() {
                    self.pet_cat(animation);
                }
                true
            }
        }
    }
    
    fn process_command(&mut self, animation: &mut PetAnimationManager) -> bool {
        // Debug命令处理 - 可通过条件编译轻松移除
        #[cfg(feature = "debug")]
        if self.input_buffer.starts_with("/debug ") {
            return self.process_debug_command(animation);
        }
        
        match self.input_buffer.as_str() {
            "/help" => {
                self.show_help = true;
                true
            },
            "/q" => {
                false // 退出游戏
            },
            "/f" => {
                self.feed_cat(animation);
                true
            },
            "/p" => {
                self.play_with_cat(animation);
                true
            },

            _ => true
        }
    }
    
    // Debug命令处理方法 - 可通过条件编译轻松移除
    #[cfg(feature = "debug")]
    fn process_debug_command(&mut self, animation: &mut PetAnimationManager) -> bool {
        // 解析 "/debug field=value" 格式
        let debug_part = &self.input_buffer[7..]; // 去掉 "/debug " 前缀
        
        if let Some((field, value_str)) = debug_part.split_once('=') {
            if let Ok(value) = value_str.parse::<i32>() {
                if self.config.debug_set_status(field, value) {
                    // 设置成功，显示反馈动画
                    animation.add_reaction_animation();
                } else {
                    // 字段名无效，显示错误动画
                    animation.add_reaction_animation();
                }
            } else {
                // 数值解析失败，显示错误动画
                animation.add_reaction_animation();
            }
        } else {
            // 格式错误，显示错误动画
            animation.add_reaction_animation();
        }
        
        true
    }
    
    fn pet_cat(&mut self, animation: &mut PetAnimationManager) {
        self.config.update_status(30, 0, -5);
        
        // 添加开心的反应动画
        animation.add_reaction_animation();
        
        // 2秒后重置动画
        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_secs(2));
        });
    }
    
    fn feed_cat(&mut self, animation: &mut PetAnimationManager) {
        // 根据宠物类型应用不同的喂食效果
        match self.config.pet_type {
            PetType::Cat(_) => {
                // 猫咪喂食效果
                self.config.update_status(
                    crate::pet_config::CAT_FEED_HAPPINESS,
                    crate::pet_config::CAT_FEED_HUNGER,
                    crate::pet_config::CAT_FEED_ENERGY
                );
                // 添加吃东西的反应动画
                animation.add_reaction_animation();
            },
            PetType::Octopus(_) => {
                // 章鱼噼喜欢吃东西
                self.config.update_status(
                    crate::pet_config::OCTOPUS_FEED_HAPPINESS,
                    crate::pet_config::OCTOPUS_FEED_HUNGER,
                    crate::pet_config::OCTOPUS_FEED_ENERGY
                );
                // 章鱼喂食时播放吃东西动画（持续10秒）
                animation.start_eating_animation_with_duration(10);
            }
        }
    }
    
    fn play_with_cat(&mut self, animation: &mut PetAnimationManager) {
        if !self.config.can_play() {
            // 睡眠中不能玩耍，添加疲惫反应
            animation.add_reaction_animation();
            return;
        }
        
        // 根据宠物类型应用不同的玩耍效果
        match self.config.pet_type {
            PetType::Cat(_) => {
                // 猫咪喜欢玩耍
                self.config.update_status(
                    crate::pet_config::CAT_PLAY_HAPPINESS,
                    crate::pet_config::CAT_PLAY_HUNGER,
                    crate::pet_config::CAT_PLAY_ENERGY
                );
            },
            PetType::Octopus(_) => {
                // 章鱼噼玩耍效果
                self.config.update_status(
                    crate::pet_config::OCTOPUS_PLAY_HAPPINESS,
                    crate::pet_config::OCTOPUS_PLAY_HUNGER,
                    crate::pet_config::OCTOPUS_PLAY_ENERGY
                );
            }
        }
        
        // 添加玩耍的反应动画
        animation.add_reaction_animation();
    }
    
    pub fn get_status(&self) -> String {
        let pet_type_name = match &self.config.pet_type {
            PetType::Cat(breed) => breed.get_name(),
            PetType::Octopus(octopus_type) => octopus_type.get_name(),
        };
        
        format!(
            "{}({}) - 心情: {} | 开心度: {} | 饱腹度: {} | 精力: {}",
            self.config.name,
            pet_type_name,
            self.config.get_mood(),
            self.config.status.happiness,
            self.config.status.hunger,
            self.config.status.energy
        )
    }
    
    pub fn get_config_mut(&mut self) -> &mut PetConfig {
        &mut self.config
    }
    
    pub fn get_config(&self) -> &PetConfig {
        &self.config
    }
    
    fn get_mood_emoji(&self) -> &'static str {
        match self.config.get_mood_state() {
            MoodState::Sleeping => "😴",
            MoodState::VeryHappy => "😄",
            MoodState::Happy => "😊",
            MoodState::Normal => "😐",
            MoodState::Unhappy => "😔",
            MoodState::VeryUnhappy => "😢",
            MoodState::Depressed => "😞",
        }
    }
    
    pub fn get_help_text(&self) -> String {
        if !self.input_buffer.is_empty() {
            format!("输入命令: {}_ ", self.input_buffer)
        } else if self.show_help {
            let mut help_text = "命令: /q 退出 | /f 喂食 | /p 玩耍".to_string();
            
            // Debug模式下添加debug命令说明
            #[cfg(feature = "debug")]
            {
                help_text.push_str(" | /debug field=value (happiness/hunger/energy)");
            }
            
            help_text.push_str(" | [Esc] 关闭帮助");
            help_text
        } else {
            format!("输入 /help 查看命令 | 任意键抚摸 {} | 状态: {}", 
                self.config.name, 
                self.get_mood_emoji())
        }
    }
    

}